//
//  FZMCCacheManager.m
//  Pods
//
//  Created by 李灿 on 15/11/11.
//
//

#import "FZMCCacheManager.h"
#import "ZipArchive.h"
#import "MCDownloadManager.h"
#import "SRCommonConstants.h"
#import "SRBookRootModel.h"
#import "SRSpeakingDatabaseManager.h"
#import "FZHomeConstants.h"

NSString *kBookInfoArrayFileName = @"kBookInfoArrayFileName";
NSString *const kBookModelJSONFileName = @"book.json";
NSString *const kBookPageImageDirName = @"bookpage";
NSString *const kBookMP3DirName = @"mp3";
NSString *const kBookTitleImageFileName = @"title.jpg";


NSString *const kAllBookRecordDirName = @"RecordDir";//Documents/RecordDir
NSString *const kBookRecordDirNamePrefix = @"bookid_";
NSString *const kBookPageRecordDirNamePrefix = @"pageid_";
NSString *const kBookPageRecordUploadCacheDir = @"uploadAudioFileCache";
NSString *const kBookCatalogueRecordDirNamePrefix = @"catalogueid_";
NSString *const kBookCatalogueWorkDirName = @"BookCatalogueWork";
NSString *const kBookCatalogueWorkDirNamePrefix = @"workid_";

@interface FZMCCacheManager ()<FZMCCacheManagerDelegate>

@property (strong, nonatomic) NSString *bookInfoFilePath;//书本信息存储文件路径
@property (strong, nonatomic) NSString *bookDownloadFileDir;//书本压缩包保存文件目录
@property (strong, nonatomic) NSString *allBookRecordDir;//音频文件录音目录

@end


@implementation FZMCCacheManager

+ (instancetype)defaultManager {
    static FZMCCacheManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
//        [sharedInstance parseGuideBook];
        
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.books = [@[] mutableCopy];
        self.bookInfoFilePath = [DocumentsDirectory appendPathComponent:kBookInfoArrayFileName];
        self.bookDownloadFileDir = [DocumentsDirectory appendPathComponent:kBookDir];
        self.allBookRecordDir = [DocumentsDirectory appendPathComponent:kAllBookRecordDirName];
        
        BOOL isDir = YES;
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:self.bookDownloadFileDir isDirectory:&isDir];
        if (!isExist || !isDir) {
                //若不存在则创建
            [[NSFileManager defaultManager] createDirectoryAtPath:self.bookDownloadFileDir withIntermediateDirectories:YES attributes:nil error:nil];
        }
        isExist = [[NSFileManager defaultManager] fileExistsAtPath:self.allBookRecordDir isDirectory:&isDir];
        if (!isExist || !isDir) {
                //若不存在则创建
            [[NSFileManager defaultManager] createDirectoryAtPath:self.allBookRecordDir withIntermediateDirectories:YES attributes:nil error:nil];
        }

    }
    
    return self;
}


#pragma mark - Book Manager



- (void)addBook:(FZHomeCourseModel *)book {
    if (!book) {
        return;
    }
    
    [self.books addObject:book];
    [self saveBookInfoToFile];
}

- (void)removeBookAtIndex:(NSInteger)index {
    if (index >= 0 && index < [self.books count]) {
        FZHomeCourseModel *model = [self.books objectAtIndex:index];
        [self removeBookCacheFileWithBookID:model.identifier];
        [self.books removeObjectAtIndex:index];
        [SRSpeakingDatabaseManager removeBookModelWithBookID:model.identifier];

        [self saveBookInfoToFile];
    }
}

- (void)removeBook:(FZHomeCourseModel *)book {
    if (!book) {
        return;
    }
    
    for (FZHomeCourseModel *model in self.books){
        if ([book.identifier isEqualToString:model.identifier]) {
            [self removeBookCacheFileWithBookID:model.identifier];
            [self.books removeObject:model];
            
            [self saveBookInfoToFile];
            break;
        }
    }
}

- (BOOL)isExistBook:(FZHomeCourseModel *)book {
    if (!book) {
        return NO;
    }
    
    for (FZHomeCourseModel *model in self.books){
        if ([book.identifier isEqualToString:model.identifier]) {
            return YES;
        }
    }
    
    
    return NO;
}

- (BOOL)isExistBookForBookID:(NSString *)bookID {
    if (!bookID) {
        return NO;
    }
    
    for (FZHomeCourseModel *model in self.books){
        if ([bookID isEqualToString:model.identifier]) {
            return YES;
        }
    }
    
    return NO;
}


- (void)removeBookCacheFileWithBookID:(NSString *)bookID {
    NSString *toPath = [self.bookDownloadFileDir appendPathComponent:bookID];
    [FZMCCacheManager removefolderFileCache:toPath];
}

- (void)removeAllBooks {
    [self.books removeAllObjects];
    [FZMCCacheManager removeFileCache:self.bookInfoFilePath];
    [FZMCCacheManager removefolderFileCache:self.bookDownloadFileDir];
    
//    [self saveBookInfoToFile];
    
    [[NSFileManager defaultManager] createDirectoryAtPath:self.bookDownloadFileDir withIntermediateDirectories:YES attributes:nil error:nil];
}

- (void)saveBookInfoToFile {
    BOOL isSuccess = [NSKeyedArchiver archiveRootObject:self.books toFile:self.bookInfoFilePath];
    if (isSuccess) {
        NSLog(@"持久化保存成功");
    } else {
        NSLog(@"持久化保存失败");
    }
}

- (void)readBookInfoFromFile {
    NSArray *books = [NSKeyedUnarchiver unarchiveObjectWithFile:self.bookInfoFilePath];
    if (books && [books isKindOfClass:[NSArray class]]) {
        [self.books removeAllObjects];
        [self.books addObjectsFromArray:books];
    }
}

- (void)startDownloadBook:(FZHomeCourseModel *)bookModel {
    WEAKSELF
    __block FZHomeCourseModel *wkBookModel = bookModel;
    
    [[MCDownloadManager defaultInstance] downloadFileWithURL:bookModel.zip progress:^(NSProgress * _Nonnull downloadProgress, MCDownloadReceipt * _Nonnull receipt) {
//        NSLog(@"progress:%f---state:%lu", downloadProgress.fractionCompleted, (unsigned long)receipt.state);
        wkBookModel.downloadState = receipt.state;
        wkBookModel.dowloadProgress = downloadProgress.fractionCompleted;
        
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(MCCacheManager:downloadPercentChangedWithModel:percent:)]) {
            [weakSelf.delegate MCCacheManager:weakSelf downloadPercentChangedWithModel:bookModel percent:downloadProgress.fractionCompleted];
        }
        
        if (wkBookModel.progressBlock) {
            wkBookModel.progressBlock(downloadProgress, receipt);
        }
        
    } destination:nil
//     ^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
////        NSString *bookDir = [DocumentsDirectory appendPathComponent:kBookDir];
//        NSString *bookDir = [NSString stringWithFormat:@"%@", bookModel.identifier];
//        NSString *bookName = [NSString stringWithFormat:@"%@_%@", bookDir, bookModel.title];
//
//        NSString *dirPath = [weakSelf.bookDownloadFileDir appendPathComponent:bookDir];
//        [FZMCCacheManager createDirWithPath:dirPath];
//        NSString *filePath = [dirPath appendPathComponent:bookName];
//        return [NSURL fileURLWithPath:filePath];
//        
//    }
    success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSURL * _Nonnull originURL, NSString *_Nonnull localFilePath) {
        if (localFilePath) {
                //解压文件
            NSString *bookID = [NSString stringWithFormat:@"%@", wkBookModel.identifier];
            NSString *toPath = [weakSelf.bookDownloadFileDir appendPathComponent:bookID];
            
//            NSLog(@"************success:id:%@------topath:%@------localPath:%@", bookID, toPath, localFilePath);
            [FZMCCacheManager zipArchiveFilePath:localFilePath toPath:toPath];
        }
        wkBookModel.downloadState = MCDownloadStateCompleted;

        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(MCCacheManager:downloadSuccessWithModel:)]) {
            [weakSelf.delegate MCCacheManager:weakSelf downloadSuccessWithModel:wkBookModel];
        }
        
        if (wkBookModel.successBlock) {
            wkBookModel.successBlock(request, response, originURL, localFilePath);
        }
        
        [weakSelf saveBookInfoToFile];
        
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
//        NSLog(@"下载失败error:%@", error);
        wkBookModel.downloadState = MCDownloadStateFailed;
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(MCCacheManager:downloadFailureWithModel:msg:)]) {
            [weakSelf.delegate MCCacheManager:weakSelf downloadFailureWithModel:bookModel msg:error.localizedDescription];
        }
        
        if (wkBookModel.failureBlock) {
            wkBookModel.failureBlock(request, response, error);
        }
        [weakSelf saveBookInfoToFile];
    }];
}

- (void)downloadAudioWithWorkModel:(SRWorkDetailModel *)bookModel
                      successBlock:(MCSucessBlock)successBlock
                      failureBlock:(MCFailureBlock)failureBlock
                     progressBlock:(MCProgressBlock)progressBlock {
//    WEAKSELF
    __block SRWorkDetailModel *wkBookModel = bookModel;
    
    [[MCDownloadManager defaultInstance] downloadFileWithURL:bookModel.audio progress:^(NSProgress * _Nonnull downloadProgress, MCDownloadReceipt * _Nonnull receipt) {
        NSLog(@"progress:%f---state:%lu", downloadProgress.fractionCompleted, (unsigned long)receipt.state);
        if (progressBlock) {
            progressBlock(downloadProgress, receipt);
        }
        
    } destination:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSURL * _Nonnull originURL, NSString *_Nonnull localFilePath) {
        if (localFilePath) {
            NSString *oldfileName = [localFilePath lastPathComponent];
            NSString *extName = [oldfileName pathExtension];
            NSString *showID = [NSString stringWithFormat:@"%@", wkBookModel.identifier];
            
            NSString *toPath = [FZMCCacheManager workMp3AudioFilePathWithShowID:showID extName:extName];
            
            [[NSFileManager defaultManager] moveItemAtPath:localFilePath toPath:toPath error:nil];
            
            if (successBlock) {
                successBlock(request, response, originURL, toPath);
            }
        }
        else {
            if (successBlock) {
                successBlock(request, response, originURL, localFilePath);
            }
        }
        
//        [weakSelf saveBookInfoToFile];
        
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
            //        NSLog(@"下载失败error:%@", error);
        if (failureBlock) {
            failureBlock(request, response, error);
        }
    }];
}

- (void)parseGuideBook {
    NSString *zipPath = [[NSBundle mainBundle] pathForResource:@"0" ofType:@"zip"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath]) {
        NSString *destPath = [self.bookDownloadFileDir appendPathComponent:kHomeGuideAlbumID];
        if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
            return;
        }
        
        BOOL isSuccess = [FZMCCacheManager zipArchiveFilePath:zipPath toPath:self.bookDownloadFileDir];
        if (isSuccess) {
            FZHomeCourseModel *guideBookModel = [[FZHomeCourseModel alloc] init];
            guideBookModel.identifier = kHomeGuideAlbumID;
            guideBookModel.title = @"试用教材";
            guideBookModel.downloadState = MCDownloadStateCompleted;
            guideBookModel.zip = @"1";
            guideBookModel.pic = @"1";
            guideBookModel.lastPageID = @"1";
            guideBookModel.gradeID = @"11";
            guideBookModel.dowloadProgress = 1;
            guideBookModel.lastPageIndex = 0;
        
            [self addBook:guideBookModel];
            
            [SRSpeakingDatabaseManager saveBookModel:guideBookModel];

        }
        
    } else {
            //不存在
        return;
    }
}

#pragma mark - Read BookFile -


    //课本信息已经下载
- (BOOL)isExistBookFile:(FZHomeCourseModel *)bookModel {
    NSString *bookID = [NSString stringWithFormat:@"%@", bookModel.identifier];
    NSString *toPath = [self.bookDownloadFileDir appendPathComponent:bookID];
    if ([[NSFileManager defaultManager] fileExistsAtPath:toPath]) {
        return YES;
    }
    
    return NO;
}

- (SRBookRootModel *)readBookModelFromDocumentWithBookID:(NSString *)bookID {
    NSString *bookIDString = [NSString stringWithFormat:@"%@", bookID];
    NSString *dirPath = [self.bookDownloadFileDir appendPathComponent:bookIDString];
    NSString *filePath = [dirPath appendPathComponent:kBookModelJSONFileName];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSError *error = nil;
        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
        if (!fileData) {
            return nil;
        }
        
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableContainers error:&error];
        if (error || !jsonData) {
            return nil;
        }
        
        SRBookRootModel *resultModel = [MTLJSONAdapter modelOfClass:[SRBookRootModel class] fromJSONDictionary:jsonData[@"book"] error:&error];
        if (error) {
            return nil;
        } else {
            return resultModel;
        }
    }
    
    return nil;
}

+ (UIImage *)pageImageWithName:(NSString *)imageName bookID:(NSString *)bookID {
    NSString *bookIDString = [NSString stringWithFormat:@"%@", bookID];
    NSString *dirPath = [[FZMCCacheManager defaultManager].bookDownloadFileDir appendPathComponent:@"%@/%@", bookIDString, kBookPageImageDirName];
    NSString *filePath = [dirPath appendPathComponent:imageName];

    UIImage *resultImage = [UIImage imageWithContentsOfFile:filePath];
    return resultImage;
}


+ (NSString *)mp3PathWithName:(NSString *)mp3Name bookID:(NSString *)bookID {
    NSString *bookIDString = [NSString stringWithFormat:@"%@", bookID];
    NSString *dirPath = [[FZMCCacheManager defaultManager].bookDownloadFileDir appendPathComponent:@"%@/%@", bookIDString, kBookMP3DirName];
    NSString *filePath = [dirPath appendPathComponent:mp3Name];
    return filePath;
}

+ (UIImage *)bookTitleImageWithBookID:(NSString *)bookID {
    NSString *bookIDString = [NSString stringWithFormat:@"%@", bookID];
    NSString *dirPath = [[FZMCCacheManager defaultManager].bookDownloadFileDir appendPathComponent:@"%@/%@", bookIDString, kBookPageImageDirName];
    NSString *filePath = [dirPath appendPathComponent:kBookTitleImageFileName];
    
    UIImage *resultImage = [UIImage imageWithContentsOfFile:filePath];
    return resultImage;
}

+ (NSString *)audioRecordFilePathWithTrackID:(NSString *)trackID pageID:(NSString *)pageID bookID:(NSString *)bookID {
    
    NSString *bookDirName = [NSString stringWithFormat:@"%@%@", kBookRecordDirNamePrefix, bookID];
    NSString *pageDirName = [NSString stringWithFormat:@"%@%@", kBookPageRecordDirNamePrefix, pageID];
    
    NSString *dirPath = [[FZMCCacheManager defaultManager].allBookRecordDir appendPathComponent:@"%@/%@", bookDirName, pageDirName];
    [self createDirWithPath:dirPath];
    
    NSString *trackName = [NSString stringWithFormat:@"%@.caf", trackID];
    NSString *filePath = [dirPath appendPathComponent:trackName];
    
    return filePath;
}

+ (NSString *)recordMp3FilePathWithTrackID:(NSString *)trackID pageID:(NSString *)pageID bookID:(NSString *)bookID  {
    NSString *audioPrefixName = [NSString stringWithFormat:@"%@_%@_%@", bookID, pageID, trackID];
    NSString *audioFileName = [NSString stringWithFormat:@"Record_%@_%@.mp3", audioPrefixName, [self dateString]];
    
        //指定新建文件夹路径
    NSString *audioPathDir = [CacheDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
        //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:audioPathDir withIntermediateDirectories:YES attributes:nil error:nil];
        //保存图片的路径
    NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:audioFileName];
    
    return audioPath;
}

+ (BOOL )removeMp3FilePathWithTrackID:(NSString *)trackID pageID:(NSString *)pageID bookID:(NSString *)bookID  {
    NSString *audioPrefixName = [NSString stringWithFormat:@"%@_%@_%@", bookID, pageID, trackID];
//    NSString *audioFileName = [NSString stringWithFormat:@"Record_%@_%@.mp3", audioPrefixName, [self dateString]];
    
        //指定新建文件夹路径
    NSString *audioPathDir = [CacheDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
//    NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:audioFileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSError *error = nil;
    NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:audioPathDir error:&error];
    
    if (error) {
        return NO;
    }
    
    for(NSString *file in dirContents) {
        if ([file containsString:audioPrefixName]) {
            NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:file];
            [self removeFileCache:audioPath];
            return YES;
        }
    }
    
    return NO;
}


+ (NSString *)isExistMp3FilePathWithTrackID:(NSString *)trackID pageID:(NSString *)pageID bookID:(NSString *)bookID  {
    NSString *audioPrefixName = [NSString stringWithFormat:@"%@_%@_%@", bookID, pageID, trackID];
        //    NSString *audioFileName = [NSString stringWithFormat:@"Record_%@_%@.mp3", audioPrefixName, [self dateString]];
    
        //指定新建文件夹路径
    NSString *audioPathDir = [CacheDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
        //    NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:audioFileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSError *error = nil;
    NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:audioPathDir error:&error];
    
    if (error) {
        return nil;
    }
    
    for(NSString *file in dirContents) {
        if ([file containsString:audioPrefixName]) {
            NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:file];
            return audioPath;
        }
    }
    return nil;
}

+ (NSString *)dateString {
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    dateFormatter.dateFormat = @"yyyy-MM-dd";
        //    NSString *dayString = [dateFormatter stringFromDate:[NSDate date]];
    NSString *timeInterval = [NSString stringWithFormat:@"%lld", (long long)[NSDate timeIntervalSince1970]];
    return [NSString stringWithFormat:@"uid%@_%@", [SRLoginUser userID], timeInterval];
}

+ (NSString *)recordComposeAudioFilePathWithCatalogueID:(NSString *)CatalogueID bookID:(NSString *)bookID  {
    NSString *audioPrefixName = [NSString stringWithFormat:@"composeAduio_%@_%@", bookID, CatalogueID];
    NSString *audioFileName = [NSString stringWithFormat:@"%@_%@.caf", audioPrefixName, [self dateString]];
    
    NSString *bookDirName = [NSString stringWithFormat:@"%@%@", kBookRecordDirNamePrefix, bookID];
    NSString *pageDirName = [NSString stringWithFormat:@"%@%@", kBookCatalogueRecordDirNamePrefix, CatalogueID];
    
    NSString *dirPath = [[FZMCCacheManager defaultManager].allBookRecordDir appendPathComponent:@"%@/%@", bookDirName, pageDirName];
    
        //指定新建文件夹路径
//    NSString *audioPathDir = [DocumentsDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
        //创建ImageFile文件夹
    if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
        //保存图片的路径
    NSString *audioPath  = [dirPath stringByAppendingPathComponent:audioFileName];
    
    return audioPath;
}

+ (NSString *)recordPageDirPathWithPageID:(NSString *)pageID bookID:(NSString *)bookID {
    NSString *bookDirName = [NSString stringWithFormat:@"%@%@", kBookRecordDirNamePrefix, bookID];
    NSString *pageDirName = [NSString stringWithFormat:@"%@%@", kBookPageRecordDirNamePrefix, pageID];
    
    NSString *dirPath = [[FZMCCacheManager defaultManager].allBookRecordDir appendPathComponent:@"%@/%@", bookDirName, pageDirName];
    
    return dirPath;
}

+ (NSString *)recordMp3AudioFilePathWithCatalogueID:(NSString *)CatalogueID bookID:(NSString *)bookID  {
    NSString *audioPrefixName = [NSString stringWithFormat:@"Aduio_%@_%@", bookID, CatalogueID];
    NSString *audioFileName = [NSString stringWithFormat:@"%@_%@.mp3", audioPrefixName, [self dateString]];
    
        //指定新建文件夹路径
    NSString *audioPathDir = [CacheDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
        //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:audioPathDir withIntermediateDirectories:YES attributes:nil error:nil];
        //保存图片的路径
    NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:audioFileName];
    
    return audioPath;
}



+ (NSString *)workMp3AudioFilePathWithShowID:(NSString *)showID extName:(NSString *)extName {
    NSString *audioFileName = [NSString stringWithFormat:@"%@.%@", showID, extName];
    
        //指定新建文件夹路径
    NSString *workDir = [CacheDirectory stringByAppendingPathComponent:kBookCatalogueWorkDirName];
    
    BOOL isDir = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:workDir isDirectory:&isDir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:workDir withIntermediateDirectories:YES attributes:nil error:nil];
    }

    NSString *audioPath  = [workDir stringByAppendingPathComponent:audioFileName];
    
    return audioPath;
}

+ (NSString *)isExistMp3FilePathWithShowID:(NSString *)showID {
//    NSString *audioPrefixName = [NSString stringWithFormat:@"%@_%@_%@", bookID, pageID, trackID];
    
        //指定新建文件夹路径
    NSString *workDir = [CacheDirectory stringByAppendingPathComponent:kBookCatalogueWorkDirName];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSError *error = nil;
    NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:workDir error:&error];
    
    if (error) {
        return nil;
    }
    
    for(NSString *file in dirContents) {
        NSString *fileName = [file stringByDeletingLastPathComponent];
        if ([fileName isEqualToString:showID]) {
            NSString *audioPath  = [workDir stringByAppendingPathComponent:file];
            return audioPath;
        }
    }
    return nil;
}

+ (NSString *)recordMp3FilePathWithProblemID:(NSString *)ProblemID{
    NSString *audioFileName = [NSString stringWithFormat:@"Record_%@_%@.aac", ProblemID, [self dateString]];
    
        //指定新建文件夹路径
    NSString *audioPathDir = [CacheDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
        //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:audioPathDir withIntermediateDirectories:YES attributes:nil error:nil];
        //保存图片的路径
    NSString *audioPath  = [audioPathDir stringByAppendingPathComponent:audioFileName];
    
    return audioPath;
}

#pragma mark - File Handle

+ (BOOL)createDirWithPath:(NSString *)path {
    BOOL isDir = YES;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
    if (!isExist || !isDir) {
            //若不存在则创建
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        
        if (error) {
            return NO;
        } else {
            return YES;
        }
    }
    
    return YES;
}

+ (NSString*)filePathAtCacheForFileName:(NSString*)fileName
{
    if (!fileName || [fileName length] <= 0) {
        return nil;
    }
    
    NSString *cacheDir = [CacheDirectory stringByAppendingPathComponent:@"AudioCache"];
        // 判断缓存目录是否存在，如果不存在，创建缓存目录；
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    if (![fileMgr fileExistsAtPath:cacheDir]) {
        [self createDirWithPath:cacheDir];
    }
    
    NSString *fileNamePath = [cacheDir stringByAppendingPathComponent:fileName];
        // 判断文件是否已经缓存在磁盘中
    if ([fileMgr fileExistsAtPath:fileNamePath]) {
        return fileNamePath;
    }
    return nil;
}

+ (float)fileCacheSizeAtPath:(NSString*)filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        long long fileSize = [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        return fileSize / (1024.0*1024.0);
    }
    return 0.0;
}

+ (float)folderCacheSizeAtPath:(NSString*)folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
    }
    return folderSize/(1024.0*1024.0);
}

+ (float)documentsCacheSizeAtPath
{
    NSString *documentsPath=[NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:documentsPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:documentsPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [documentsPath stringByAppendingPathComponent:fileName];
        folderSize += [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
    }
    return folderSize/(1024.0*1024.0);
}

+ (float)cacheSizeAtPath
{//  使用NSSearchPathForDirectoriesInDomains只能定位Caches目录和Documents目录。
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:cachPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:cachPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [cachPath stringByAppendingPathComponent:fileName];
        folderSize += [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
    }
    return folderSize/(1024.0*1024.0);
}

+ (float)cardCacheSizePath
{
    NSString *documentsPath=[NSString stringWithFormat:@"%@/Documents/cacheCardPath",NSHomeDirectory()];
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:documentsPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:documentsPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [documentsPath stringByAppendingPathComponent:fileName];
        folderSize += [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
    }
    return folderSize;
}

+ (void)removeFileCache:(NSString *)filePath
{
    NSError *error;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
    }
}

+ (void)removefolderFileCache:(NSString *)filePath
{
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:filePath];
    for (NSString *file in files) {
        NSError *error;
        NSString *path = [filePath stringByAppendingPathComponent:file];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}

+ (void)removeDocumentsFileCache
{
    NSString *documentsPath=[NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:documentsPath];
    for (NSString *filePath in files) {
        NSError *error;
        NSString *path = [documentsPath stringByAppendingPathComponent:filePath];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}

+ (void)removeCacheFileCache
{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    for (NSString *filePath in files) {
        NSError *error;
        NSString *path = [cachPath stringByAppendingPathComponent:filePath];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}

+ (void)removeCache
{
    NSURLCache *cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
}

+ (void)removeUploadRecordCache {
    NSString *audioPathDir = [CacheDirectory stringByAppendingPathComponent:kBookPageRecordUploadCacheDir];
    [self removefolderFileCache:audioPathDir];
}

+ (BOOL)zipArchiveFilePath:(NSString *)zipPath toPath:(NSString *)toPath{
    [self removefolderFileCache:toPath];
    
    BOOL isSuccess = [SSZipArchive unzipFileAtPath:zipPath toDestination: toPath];
    if (isSuccess) {
            //解压成功
    } else {
            //解压失败
        
    }
    [self removeFileCache:zipPath];//解压后删除缓存文件
    
    return isSuccess;
}

@end
